package com.felix.tests;

import com.ghgande.j2mod.modbus.msg.ModbusResponse;
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersResponse;
import com.ghgande.j2mod.modbus.procimg.Register;
import felix.things.router.modbus.response.ModBusResponseProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;


@Component
@Slf4j
public class ModBusByteResponseProcessor implements ModBusResponseProcessor {
    @Override
    public ModbusResponse processorResponse(String tag, ModbusResponse response, int start, int end) {
        String hexMessage = response.getHexMessage();
        if (response instanceof ReadMultipleRegistersResponse) {
            ReadMultipleRegistersResponse data = (ReadMultipleRegistersResponse) response;
            Register[] values = data.getRegisters();
            for (Register value : values) {
                String s = Integer.toBinaryString(value.toUnsignedShort());
                System.out.println(addZeroForNum(s, 16));
            }
            log.debug("【{}】:Data: 【{}】", tag, Arrays.toString(values));
        }
        return response;
    }

    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左补0
                // sb.append(str).append("0");//右补0
                str = sb.toString();
                strLen = str.length();
            }
        }

        return str;
    }


    @Override
    public String getTag() {
        return "tcp:qinghe";
    }
}
